package com.motu.vertx.module.utility.trino;

import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.SQLClient;
import io.vertx.ext.sql.SQLConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class TrinoTool {
    private static final Logger logger = LoggerFactory.getLogger(TrinoTool.class);

    public static SQLClient initTrinoJDBC(Vertx vertx, JsonObject appConfig){
        JsonObject jsonConfig = appConfig.getJsonObject("trino-clickhouse");
        JsonObject config = new JsonObject()
                .put("url", jsonConfig.getString("url"))
                .put("driver_class",  jsonConfig.getString("driver_class"))
                .put("user",  jsonConfig.getString("user"))
                .put("password",  jsonConfig.getString("password"))
                .put("max_pool_size",  jsonConfig.getInteger("max_pool_size"));

        return JDBCClient.createShared(vertx, config);
    }
    /***
     * 查询数据库，返回异步结果
     * @param jdbcClient
     * @param sql
     * @param params
     * @param handler
     */
    public static void queryJsonArrayFromDb(SQLClient jdbcClient, String sql, JsonArray params, Handler<AsyncResult<JsonArray>> handler) {
        if (jdbcClient == null) {
            handler.handle(Future.failedFuture("jdbcClient is null"));
        } else {
            jdbcClient.queryWithParams(sql, params, res -> {
                if (res.succeeded()) {
                    List<JsonObject> rows = res.result().getRows();
                    if (rows.isEmpty()) {
                        handler.handle(Future.succeededFuture(new JsonArray()));
                    } else {
                        JsonArray array = new JsonArray(rows);
                        handler.handle(Future.succeededFuture(array));
                    }
                } else {
                    logger.error("----############---- trino sql:" + sql + " params:" + params.toString() + " " + res.cause().getMessage());
                    res.cause().printStackTrace();
                    handler.handle(Future.failedFuture(res.cause().getMessage()));
                }
            });
        }
    }

    /***
     * 更新到数据库
     * @param jdbcClient
     * @param sql
     * @param params
     * @param handler
     */
    public static void updateToDb(SQLClient jdbcClient, String sql, JsonArray params, Handler<AsyncResult<Object>> handler) {
        jdbcClient.updateWithParams(sql, params, res -> {
            if (res.succeeded()) {
                handler.handle(Future.succeededFuture(res.result().getUpdated()));
            } else {
                logger.error("----############---- trino sql:" + sql + " params:" + params.toString() + " " + res.cause().getMessage());
                res.cause().printStackTrace();
                handler.handle(Future.failedFuture(res.cause().getMessage()));
            }
        });

    }

    /***
     * 批量入库,trino不支持
     * @param jdbcClient
     * @param sqlList
     * @param handler
     */
    public static void batchToDb(SQLClient jdbcClient, List<String> sqlList, Handler<AsyncResult<Void>> handler) {

        jdbcClient.getConnection(res -> {
            if (res.succeeded()) {
                System.out.println("getConnection ok ");
                SQLConnection connection = res.result();
                connection.batch(sqlList, res2 -> {
                    if (res2.failed()) {
                        logger.error(res2.cause().getMessage());
                        handler.handle(Future.failedFuture(res2.cause().getMessage()));
                    }else{
                        handler.handle(Future.succeededFuture());
                    }
                });
            } else {
                logger.error(res.cause().getMessage());
                handler.handle(Future.failedFuture(res.cause().getMessage()));
            }
        });

    }
}
